package task;

import com.book.constrains.SystemConstants;
import com.book.pojo.Book;
import com.book.pojo.BorrowRecord;
import com.book.pojo.Reader;
import com.book.protocol.Protocol;
import com.book.service.ReaderService;
import com.book.service.impl.ReaderServiceImpl;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.List;

public class ReaderTaskThread implements Runnable {
    //代表用户的套接字对象
    private Socket readerClient;
    //业务层对象
    private ReaderService readerService = new ReaderServiceImpl();
    //通信协议对象
    private Protocol<Object> protocol;
    public ReaderTaskThread(Socket readerClient, Protocol<Object> protocol) {
        this.readerClient = readerClient;
        this.protocol = protocol;
    }

    @Override
    public void run() {
        while (true) {
            if(null == protocol){
                try {
                    //后续多次操作，重新获取协议对象
                    ObjectInputStream ois = new ObjectInputStream(readerClient.getInputStream());
                    protocol = (Protocol<Object>) ois.readObject();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } catch (ClassNotFoundException e) {
                    throw new RuntimeException(e);
                }
            }
            switch (protocol.getOpt()){
                case SystemConstants.READER_LOGIN://用户登陆
                    readerLogin();
                    break;
                case SystemConstants.READER_RETURN_BOOK://还书
                    returnBook();
                    break;
                case SystemConstants.READER_FINDALL_BOOKS://查询所有书籍
                    findAllBooks();
                    break;
                case SystemConstants.READER_BORROW_BOOK://借书
                    addBorrowRecord();
                    break;
                case SystemConstants.READER_VIEW_BORROWED_BOOKS://查看自己借的书
                    findBorrowRecordsByReaderId();
                    break;
            }
        }
    }

    //查看自己借了啥书
    private void findBorrowRecordsByReaderId(){
        try {
            BorrowRecord reader = (BorrowRecord) protocol.getData();
            List<BorrowRecord> books = readerService.findBorrowRecordsByReaderId(reader.getReaderId());
            Protocol<String> backProtocol = new Protocol<>();

            if (books != null && !books.isEmpty()) {
                backProtocol.setCode(SystemConstants.Code.OPT_SUCCESS);
                backProtocol.setMsg("查询成功，共找到 " + books.size() + " 本书！");

                // 格式化输出
                StringBuilder result = new StringBuilder();
                result.append("查询到的图书信息如下：\n");
                result.append("--------------------------------------------------\n");
                result.append(String.format("%-5s %-5s %-5s %-5s %-5s %-5s\n", "图书ID", "读者id", "借阅日期","借阅时间",
                        "归还日期","归还时间"));
                result.append("--------------------------------------------------\n");
                for (BorrowRecord book : books) {
                    result.append(String.format("%-5d %-5d %tF %tT %tF %tT\n",
                            book.getBookId(), book.getReaderId(),book.getBorrowDate(),book.getBorrowDate(),
                            book.getReturnDate(),book.getReturnDate()));
                }
                result.append("--------------------------------------------------");

                backProtocol.setData(result.toString());
                //System.out.println(result.toString()); // 服务器打印美化后的查询结果
            } else {
                backProtocol.setCode(SystemConstants.Code.OPT_FAILURE);
                backProtocol.setMsg("没有找到任何书籍！");
                backProtocol.setData("暂无书籍信息！");
            }

            // 发送响应
            ObjectOutputStream oos = new ObjectOutputStream(readerClient.getOutputStream());
            oos.writeObject(backProtocol);
            oos.flush();
            this.protocol=null;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    //查询所有图书
    private void findAllBooks(){
        try {


            List<Book> books = readerService.findAllBooks();
            Protocol<String> backProtocol = new Protocol<>();

            if (books != null && !books.isEmpty()) {
                backProtocol.setCode(SystemConstants.Code.OPT_SUCCESS);
                backProtocol.setMsg("查询成功，共找到 " + books.size() + " 本书！");

                // 格式化输出
                StringBuilder result = new StringBuilder();
                result.append("查询到的图书信息如下：\n");
                result.append("--------------------------------------------------\n");
                result.append(String.format("%-5s %-20s %-20s %-10s\n", "ID", "书名", "作者", "可借状态"));
                result.append("--------------------------------------------------\n");
                for (Book book : books) {
                    result.append(String.format("%-5d %-20s %-20s %-10s\n",
                            book.getId(), book.getTitle(), book.getAuthor(), book.isAvailable() ? "可借" : "不可借"));
                }
                result.append("--------------------------------------------------");

                backProtocol.setData(result.toString());
               // System.out.println(result.toString()); // 服务器打印美化后的查询结果
            } else {
                backProtocol.setCode(SystemConstants.Code.OPT_FAILURE);
                backProtocol.setMsg("没有找到任何书籍！");
                backProtocol.setData("暂无书籍信息！");
            }

            // 发送响应
            ObjectOutputStream oos = new ObjectOutputStream(readerClient.getOutputStream());
            oos.writeObject(backProtocol);
            oos.flush();
            this.protocol=null;
        } catch (IOException e) {
            System.err.println("查询图书过程中出现 IO 错误：" + e.getMessage());
            e.printStackTrace();
        } catch (Exception e) {
            System.err.println("查询图书过程中发生异常：" + e.getMessage());
            e.printStackTrace();
        }
    }
    //借书
    private void addBorrowRecord() {
        try {
            //获取信息
            BorrowRecord book = (BorrowRecord) protocol.getData();
            int row = readerService.addBorrowRecord(book);
            protocol = new Protocol();
            //取得客户端输出流对象
            ObjectOutputStream oos = new ObjectOutputStream(readerClient.getOutputStream());
            //写出响应协议对象
            protocol.setMsg(row==1?"图书借阅成功":"图书借阅失败");
            protocol.setCode(row==1?SystemConstants.Code.OPT_SUCCESS:SystemConstants.Code.OPT_FAILURE);
            oos.writeObject(protocol);
            oos.flush();
            //清空协议对象
            protocol = null;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    //还书
    private void returnBook(){
        try {
            //获取信息
            BorrowRecord book = (BorrowRecord) protocol.getData();
            int row = readerService.returnBook(book.getBookId());
            protocol = new Protocol();
            //取得客户端输出流对象
            ObjectOutputStream oos = new ObjectOutputStream(readerClient.getOutputStream());
            //写出响应协议对象
            protocol.setMsg(row==1?"图书归还成功":"图书归还失败");
            protocol.setCode(row==1?SystemConstants.Code.OPT_SUCCESS:SystemConstants.Code.OPT_FAILURE);
            oos.writeObject(protocol);
            oos.flush();
            //清空协议对象
            protocol = null;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
    //用户登录
    private void readerLogin() {
        try {
            Reader reader = (Reader) protocol.getData();
            Reader loginReader = readerService.login(reader);
            Protocol backProtocol = new Protocol();
            if(loginReader != null){
                //登陆成功
                backProtocol.setMsg("登陆成功");
                backProtocol.setCode(SystemConstants.Code.OPT_SUCCESS);
            }else{
                //登录失败
                backProtocol.setMsg("登录失败！");
                backProtocol.setCode(SystemConstants.Code.OPT_FAILURE);
            }
            //将结果封装发给客户端
            ObjectOutputStream oos = new ObjectOutputStream(readerClient.getOutputStream());
            oos.writeObject(backProtocol);
            oos.flush();
            //清空协议对象
            this.protocol=null;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
